package com.jmu.edu.IMApplication.fragment;

import android.graphics.Bitmap;
import android.os.Bundle;

import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import android.util.Log;
import android.view.GestureDetector;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.jmu.edu.IMApplication.MainActivity;
import com.jmu.edu.IMApplication.MyApplication;
import com.jmu.edu.IMApplication.R;
import com.jmu.edu.IMApplication.adapter.MessageItemAdapter;
import com.jmu.edu.IMApplication.adapter.SwipeMessageItemAdapter;
import com.jmu.edu.IMApplication.utils.MsgUtils;
import com.jmu.edu.IMApplication.utils.ViewUtils;
import com.jmu.edu.IMApplication.utils.WillowUtils;

import java.util.ArrayList;
import java.util.List;

import cn.jpush.im.android.api.JMessageClient;
import cn.jpush.im.android.api.callback.GetAvatarBitmapCallback;
import cn.jpush.im.android.api.event.CommandNotificationEvent;
import cn.jpush.im.android.api.event.ConversationRefreshEvent;
import cn.jpush.im.android.api.event.MessageEvent;
import cn.jpush.im.android.api.model.Conversation;
import cn.jpush.im.android.api.model.Message;
import jackmego.com.jieba_android.JiebaSegmenter;


public class MessageFragment extends Fragment {
    // 联系人列表，用来填充到list中进行展示
    private List<Conversation> conversationList;

    private RecyclerView recyclerView;
    private SwipeRefreshLayout swipeRefreshLayout;
    private MessageItemAdapter adapter;

    private GestureDetector gestureDetector;

    public MessageFragment() {
        // Required empty public constructor
    }


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        WillowUtils.registerEventReceiver(this);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        conversationList = new ArrayList<>();

        return inflater.inflate(R.layout.fragment_message, container, false);
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        swipeRefreshLayout = getView().findViewById(R.id.fragment_message_refresh_layout);
        initListener();
        recyclerView = getView().findViewById(R.id.fragment_message_recyclerView);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getContext());
        linearLayoutManager.setOrientation(RecyclerView.VERTICAL);
        recyclerView.setLayoutManager(linearLayoutManager);
        adapter = new MessageItemAdapter();

        loadData();
        recyclerView.setAdapter(adapter);
    }

    private void initListener() {
        gestureDetector = new GestureDetector(getContext(), new GestureDetector.SimpleOnGestureListener() {
            @Override
            public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
                float xToLeft = e1.getX() - e2.getX();
                float xToRight = e2.getX() - e1.getX();
                //如果向左移动的距离大于最小移动距离且移动速度大于最小移动速度，那么满足左滑手势的条件,反之满足向右滑动
                if (xToLeft > ViewUtils.MIN_FLING_DISTANCE && Math.abs(velocityX) > ViewUtils.MIN_FLING_VELOCITY) {
                    return false;
                } else if (xToRight > ViewUtils.MIN_FLING_DISTANCE && Math.abs(velocityX) > ViewUtils.MIN_FLING_VELOCITY) {
                    ViewUtils.showMyFragment();
                    return true;
                }
                return false;
            }
        });
        //添加右滑监听->切换到MyFragment
        getView().setLongClickable(true);
        getView().setFocusable(true);
        getView().setFocusableInTouchMode(true);
        getView().setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                return gestureDetector.onTouchEvent(event);
            }
        });
        //添加刷新监听
        swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                //重载数据，并提醒recycle进行数据更新
                loadData();
                adapter.notifyDataSetChanged();
                //关闭刷新动画
                swipeRefreshLayout.setRefreshing(false);

            }
        });
    }

    /**
     * 加载ListView的数据
     */
    public void loadData() {
        conversationList = MsgUtils.getConversationList();
        if (conversationList == null) {
            System.out.println("error---");
        } else if (conversationList.isEmpty()) {
            Log.d("聊天列表", "空的");
        } else {
            Log.d("聊天列表", conversationList.size() + "");
            adapter.setConversationList(conversationList);
        }
    }

    public void onEventMainThread(MessageEvent messageEvent) {
        Message newMessage = messageEvent.getMessage();//获取此次离线期间会话收到的新消息列表
        Log.d("消息监听", "收到了消息:" + newMessage.getContent().toJson());
        refreshData();
    }

    public void onEventMainThread(ConversationRefreshEvent conversationRefreshEvent) {
        Log.d("消息监听", "收到了会话刷新消息:" + conversationRefreshEvent.getReason());
        refreshData();
    }

//    public void onEventMainThread(CommandNotificationEvent commandNotificationEvent) {
//        if(commandNotificationEvent.getMsg().equals("refresh"))
//        {
//            refreshData();
//        }
//        Log.d("消息监听", "收到了消息:"+commandNotificationEvent.getMsg());
//
//    }

    public void refreshData() {
        Log.d("test", "refresh");
        loadData();
        if (adapter.getConversationList() != null) {
            adapter.notifyDataSetChanged();
        }

    }
}